<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use cmf\controller\RestAdminBaseController;
use think\Db;
use think\Validate;
use app\admin\model\AuthRuleModel;
use app\admin\model\AdminMenuModel;

class PublicController extends RestAdminBaseController
{
    //去掉登录限制
    public function _initialize()
    {

    }

    // 用户登录 TODO 增加最后登录信息记录,如 ip
    public function login()
    {
        $captcha = $this->request->param('captcha');
        if (empty($captcha)) {
            $this->error(lang('CAPTCHA_REQUIRED'));
        }
        //验证码
        if (!cmf_captcha_check($captcha)) {
            $this->error(lang('CAPTCHA_NOT_RIGHT'));
        }

        $validate = new Validate([
            'username' => 'require',
            'password' => 'require'
        ]);
        $validate->message([
            'username.require' => '请输入手机号,邮箱或用户名!',
            'password.require' => '请输入您的密码!'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $userQuery = Db::name("user");
        if (Validate::is($data['username'], 'email')) {
            $userQuery = $userQuery->where('user_email', $data['username']);
        } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
            $userQuery = $userQuery->where('mobile', $data['username']);
        } else {
            $userQuery = $userQuery->where('user_login', $data['username']);
        }

        $findUser = $userQuery->find();

        if (empty($findUser)) {
            $this->error(lang('USERNAME_NOT_EXIST'));
        } else {

            switch ($findUser['user_status']) {
                case 0:
                    $this->error('您已被拉黑!');
                case 2:
                    $this->error('账户还没有验证成功!');
            }

            if (!cmf_compare_password($data['password'], $findUser['user_pass'])) {
                $this->error("密码不正确!");
            }
        }

        $allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac'];

        if (empty($data['device_type']) || !in_array($data['device_type'], $allowedDeviceTypes)) {
            $this->error("请求错误,未知设备!");
        }

        $userTokenQuery = Db::name("user_token")
            ->where('user_id', $findUser['id'])
            ->where('device_type', $data['device_type']);
        $findUserToken  = $userTokenQuery->find();
        $currentTime    = time();
        $expireTime     = $currentTime + 24 * 3600 * 180;
        $token          = md5(uniqid()) . md5(uniqid());
        if (empty($findUserToken)) {
            $result = $userTokenQuery->insert([
                'token'       => $token,
                'user_id'     => $findUser['id'],
                'expire_time' => $expireTime,
                'create_time' => $currentTime,
                'device_type' => $data['device_type']
            ]);
        } else {
            $result = $userTokenQuery
                ->where('user_id', $findUser['id'])
                ->where('device_type', $data['device_type'])
                ->update([
                    'token'       => $token,
                    'expire_time' => $expireTime,
                    'create_time' => $currentTime
                ]);
        }

        if (empty($result)) {
            $this->error("登录失败!");
        }
        session('ADMIN_ID', $findUser['id']);
        $this->success(lang('LOGIN_SUCCESS'), ['token' => $token ]);
    }

    /**
     * 登录验证
     */
    public function doLogin()
    {
        $loginAllowed = session("__LOGIN_BY_CMF_ADMIN_PW__");
        if (empty($loginAllowed)) {
            $this->error('非法登录!', cmf_get_root() . '/');
        }

        $captcha = $this->request->param('captcha');
        if (empty($captcha)) {
            $this->error(lang('CAPTCHA_REQUIRED'));
        }
        //验证码
        if (!cmf_captcha_check($captcha)) {
            $this->error(lang('CAPTCHA_NOT_RIGHT'));
        }

        $name = $this->request->param("username");
        if (empty($name)) {
            $this->error(lang('USERNAME_OR_EMAIL_EMPTY'));
        }
        $pass = $this->request->param("password");
        if (empty($pass)) {
            $this->error(lang('PASSWORD_REQUIRED'));
        }
        if (strpos($name, "@") > 0) {//邮箱登陆
            $where['user_email'] = $name;
        } else {
            $where['user_login'] = $name;
        }

        $result = Db::name('user')->where($where)->find();

        if (!empty($result) && $result['user_type'] == 1) {
            if (cmf_compare_password($pass, $result['user_pass'])) {
                $groups = Db::name('RoleUser')
                    ->alias("a")
                    ->join('__ROLE__ b', 'a.role_id =b.id')
                    ->where(["user_id" => $result["id"], "status" => 1])
                    ->value("role_id");
                if ($result["id"] != 1 && (empty($groups) || empty($result['user_status']))) {
                    $this->error(lang('USE_DISABLED'));
                }
                //登入成功页面跳转
                session('ADMIN_ID', $result["id"]);
                session('name', $result["user_login"]);
                $result['last_login_ip']   = get_client_ip(0, true);
                $result['last_login_time'] = time();
                $token                     = cmf_generate_user_token($result["id"], 'web');
                if (!empty($token)) {
                    session('token', $token);
                }
                Db::name('user')->update($result);
                cookie("admin_username", $name, 3600 * 24 * 30);
                session("__LOGIN_BY_CMF_ADMIN_PW__", null);
                $this->success(lang('LOGIN_SUCCESS'), url("admin/Index/index"));
            } else {
                $this->error(lang('PASSWORD_NOT_RIGHT'));
            }
        } else {
            $this->error(lang('USERNAME_NOT_EXIST'));
        }
    }



    // 管理员退出
    public function logout()
    {
        $userId = $this->getUserId();
        Db::name('user_token')->where([
            'token'       => $this->token,
            'user_id'     => $userId,
            'device_type' => $this->deviceType
        ])->update(['token' => '', 'expire_time' => 0]);
        session('ADMIN_ID', null);
        $this->success("退出成功!");
    }

    //用户信息
    public function userInfo(){
        $user = $this->user;
        if (!empty($user) && $user['user_type'] == 1) {
            $groups = Db::name('RoleUser')
                ->alias("a")
                ->join('__ROLE__ b', 'a.role_id =b.id')
                ->where(["user_id" => $user["id"], "status" => 1])
                ->value("role_id");
            if ($user["id"] != 1 && (empty($groups) || empty($user['user_status']))) {
                $this->error(lang('USE_DISABLED'));
            }
            if($user["id"] == 1){
                $groups = [1];
            }

            $authRuleModel = new AuthRuleModel();
           $authRules    = cache('admin_auth_rules_' . cmf_get_current_admin_id(), '', null, 'admin_auth_rules');

            if(empty($auth_rules)){
                $authRules = $authRuleModel->adminAuthRule();
                cache('admin_auth_rules_' . cmf_get_current_admin_id(), $authRules, null, 'admin_auth_rules');
            }

            $adminMenuModel = new AdminMenuModel();
            $menus          = cache('admin_menus_' . cmf_get_current_admin_id(), '', null, 'admin_menus');

            if (empty($menus)) {
                $menus = $adminMenuModel->menuTree();
                cache('admin_menus_' . cmf_get_current_admin_id(), $menus, null, 'admin_menus');
            }

            $this->success(lang('LOGIN_SUCCESS'),['auth_rules'=> $authRules,'menus'=>$menus,'name'=>$user['user_login'],'avatar'=>$user['avatar']]);
        }else{
            $this->error(lang('您还未登录或者用户类型不正确'));
        }
    }

    // 获取验证码图片地址
    public function captchaUrl(){
        $this->success('SUCCESS', $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].'/captcha/new.html');
    }

}
